Popular Searches
Popular Course Categories
Popular Courses

Creating and Using Custom JSP Tags

Creating and Using Custom JSP Tags

JSP Expression Language, JSTL, and Custom Tags

Creating and Using Custom JSP Tags

Course: Advanced Java Training

Topic: Creating and Using Custom JSP Tags

Course Link: Advanced Java Training Course

Demo Link: Register for a Free Course Demo

Website: JustAcademy


1. Introduction to Custom JSP Tags

JavaServer Pages (JSP) is a server-side technology used to create dynamic web pages using Java and HTML. JSP supports standard actions, Expression Language (EL), and the JavaServer Pages Standard Tag Library (JSTL). Developers can also create custom JSP tags to encapsulate reusable presentation logic and make JSP pages easier to read and maintain.

A custom JSP tag is a user-defined tag that can be used in a JSP page much like a built-in HTML element or JSTL tag. Instead of repeatedly writing the same Java or presentation logic in multiple JSP files, developers can place that functionality inside a reusable tag.

For example, a website may repeatedly display a welcome message, format a price, show a reusable page header, or render a common information panel. Custom tags allow these tasks to be packaged into reusable components.

Example of a Custom Tag in a JSP Page

<%@ taglib prefix="my" uri="https://example.com/tags" %>

<html>
<body>
    <my:welcome name="Student" />
</body>
</html>

In this example, my is the tag prefix, welcome is the custom tag name, and name is an attribute passed to the tag. The tag implementation determines what output is generated.

2. Learning Objectives

  • Understand the purpose and benefits of custom JSP tags.
  • Identify the main approaches to creating custom tags.
  • Create reusable tags using JSP tag files.
  • Create Java-based custom tags using SimpleTagSupport.
  • Understand Tag Library Descriptor (TLD) files.
  • Pass values through tag attributes.
  • Process tag bodies and work with nested content.
  • Apply custom tags to reusable web application components.
  • Recognize common errors and follow tag-development best practices.

3. Why Are Custom JSP Tags Needed?

Without reusable tags, developers may repeat the same presentation code across several JSP pages. This increases maintenance effort and can lead to inconsistent output. Custom tags provide a structured way to reuse that logic.

Problem How Custom Tags Help
Repeated presentation code Encapsulate reusable output in one tag.
Complex JSP pages Move implementation details out of the page.
Inconsistent formatting Centralize shared presentation rules.
Difficult maintenance Update the implementation in one place.
Repeated UI components Reuse headers, labels, messages, and panels.

4. Types of Custom JSP Tags

There are two common approaches for creating reusable JSP tags: JSP tag files and Java-based tag handlers.

4.1 JSP Tag Files

A tag file is a JSP-like file with the .tag or .tagx extension. It defines reusable presentation logic using JSP tag syntax, directives, EL, and other supported JSP features. Tag files are often convenient for reusable page fragments and UI components.

Example file: /WEB-INF/tags/message.tag

4.2 Java-Based Custom Tags

A Java-based tag handler is a Java class that implements the JSP tag extension API. A simple tag handler can extend SimpleTagSupport and implement the doTag() method. A Tag Library Descriptor (TLD) can associate the Java class with a tag name and define its attributes.

This approach is useful when the tag needs Java logic, structured processing, or integration with application services.

4.3 Choosing an Approach

Feature Tag File Java Tag Handler
Implementation language JSP tag syntax, EL, and supported JSP features Java
Typical use Reusable presentation fragments Reusable logic and custom processing
Setup Usually simpler Usually requires a Java class and tag registration
Presentation flexibility High for markup-oriented components Output can be generated programmatically
Example Reusable message panel Formatted welcome message

5. Understanding the JSP Tag Lifecycle

The JSP container manages the execution of custom tags. The exact lifecycle depends on the type of tag handler being used.

Simple Tag Handler Lifecycle

  1. The JSP page uses a custom tag.
  2. The JSP container identifies the tag library and its implementation.
  3. The container creates and configures the tag handler.
  4. The container supplies the tag's attributes.
  5. The container invokes doTag().
  6. The handler performs its work and may write output.
  7. The container completes processing and releases the handler according to the JSP specification.

Important: A simple tag handler uses doTag(). The classic tag-handler lifecycle methods, such as doStartTag() and doEndTag(), belong to the older, classic tag extension model and should not be mixed with the simple tag API.

6. Creating a Custom JSP Tag Using a Tag File

Tag files are a straightforward way to create reusable presentation components without writing a Java tag-handler class.

Step 1: Create the Tag Directory

Inside the web application, create the following directory:

src/main/webapp/
    WEB-INF/
        tags/

The /WEB-INF/tags directory is a conventional location for JSP tag files that are made available through a JSP tag directive.

Step 2: Create a Tag File

Create a file named greeting.tag inside /WEB-INF/tags.

<%@ tag body-content="empty" %>
<%@ attribute name="name" required="true" %>

<div>
    <h3>Welcome, ${name}!</h3>
    <p>Thank you for visiting our website.</p>
</div>

Explanation:

  • <%@ tag %> declares tag-file configuration.
  • body-content="empty" indicates that the tag is not intended to contain a body.
  • <%@ attribute %> declares the tag's name attribute.
  • required="true" indicates that callers must supply the attribute.
  • ${name} uses Expression Language to display the supplied value.

For applications that display user-controlled values, use appropriate output escaping. When rendering plain text, JSTL's <c:out> is commonly used to escape XML-sensitive characters.

Step 3: Use the Tag File in a JSP Page

Create or update index.jsp:

<%@ taglib prefix="custom" tagdir="/WEB-INF/tags" %>
<!DOCTYPE html>
<html>
<head>
    <title>Custom JSP Tag Example</title>
</head>
<body>
    <custom:greeting name="Student" />
</body>
</html>

The JSP container locates greeting.tag and executes it when the page is rendered. The page displays a welcome message using the supplied attribute.

Step 4: Test the Application

  1. Deploy the application to a compatible Jakarta Servlet and JSP container.
  2. Open the JSP page in a browser.
  3. Confirm that the welcome message appears.
  4. Change the name attribute and test the output again.
  5. Check server logs if the tag file cannot be resolved or compiled.

7. Creating a Java-Based Custom JSP Tag

Java-based tags are useful when the tag needs to perform processing that is easier to implement in Java. The following example uses the Jakarta JSP API namespace.

Step 1: Create a Java Tag Handler

Create a class named WelcomeTag.java in the package com.example.tags.

package com.example.tags;

import java.io.IOException;
import jakarta.servlet.jsp.JspException;
import jakarta.servlet.jsp.JspWriter;
import jakarta.servlet.jsp.tagext.SimpleTagSupport;

public class WelcomeTag extends SimpleTagSupport {

    private String name;

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public void doTag() throws JspException, IOException {
        JspWriter out = getJspContext().getOut();

        String safeName = escapeHtml(name == null ? "Guest" : name);
        out.write("<div class=\"welcome-message\">");
        out.write("<h3>Welcome, " + safeName + "!</h3>");
        out.write("</div>");
    }

    private String escapeHtml(String value) {
        return value
            .replace("&", "&amp;")
            .replace("<", "&lt;")
            .replace(">", "&gt;")
            .replace(""", "&quot;")
            .replace("'", "'");
    }
}

Code explanation:

  • SimpleTagSupport provides a convenient base class for implementing simple JSP tags.
  • name stores the value supplied by the JSP page.
  • setName() allows the JSP container to assign the tag attribute.
  • doTag() contains the tag's execution logic.
  • getJspContext().getOut() obtains a writer for producing JSP output.
  • escapeHtml() illustrates escaping common HTML-sensitive characters before writing a value into HTML text.

Note: This escaping helper is a small teaching example for HTML text content, not a general-purpose encoder for every output context. In production, prefer a well-tested context-aware escaping library and avoid constructing HTML with untrusted values wherever possible.

Step 2: Create a Tag Library Descriptor

A Tag Library Descriptor (TLD) is an XML file that describes a tag library, its tags, their implementation classes, and supported attributes.

Create /WEB-INF/my-tags.tld:

<?xml version="1.0" encoding="UTF-8"?>
<taglib xmlns="https://jakarta.ee/xml/ns/jakartaee"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee
        https://jakarta.ee/xml/ns/jakartaee/web-jsptaglibrary_3_0.xsd"
        version="3.0">

    <tlib-version>1.0</tlib-version>
    <short-name>mytags</short-name>
    <uri>https://example.com/tags</uri>

    <tag>
        <name>welcome</name>
        <tag-class>com.example.tags.WelcomeTag</tag-class>
        <body-content>empty</body-content>

        <attribute>
            <name>name</name>
            <required>true</required>
            <rtexprvalue>true</rtexprvalue>
        </attribute>
    </tag>
</taglib>

Important TLD elements:

Element Purpose
<taglib> Root element describing the tag library.
<tlib-version> Identifies the version of the custom tag library.
<short-name> Provides a short name for the library.
<uri> Provides the tag library identifier used by the JSP directive.
<tag> Defines an individual custom tag.
<name> Defines the tag name used in JSP.
<tag-class> Specifies the fully qualified Java tag-handler class.
<attribute> Describes an attribute supported by the tag.
<required> Indicates whether the attribute must be provided.
<rtexprvalue> Indicates whether runtime expressions can supply the attribute value.

Step 3: Register and Use the Tag Library

In a JSP page, use the URI declared in the TLD:

<%@ taglib prefix="my" uri="https://example.com/tags" %>

<!DOCTYPE html>
<html>
<head>
    <title>Java Custom Tag</title>
</head>
<body>
    <my:welcome name="Aarav" />
</body>
</html>

When the JSP container processes this page, it resolves the tag library, creates the tag handler, sets the name attribute, and invokes doTag().

8. Understanding Tag Attributes

Attributes allow JSP developers to pass information into custom tags. A tag can use attributes to customize its output or behavior.

For a Java tag handler, an attribute is commonly represented by a private field and a public setter method. The setter name must follow JavaBean conventions so that the JSP container can recognize it.

private String message;

public void setMessage(String message) {
    this.message = message;
}

The tag can then be used as follows:

<my:message message="Your registration was successful." />

Common Attribute Settings

  • Required: Specifies whether the caller must supply the attribute.
  • Type: Can declare the expected Java type for a tag attribute in a TLD.
  • Runtime expression support: Determines whether expressions can provide values, according to the descriptor configuration.
  • Default behavior: The handler can define behavior for missing or null values when the attribute is optional.

9. Processing the Body of a Custom Tag

Some tags need content between their opening and closing tags. This content is called the tag body.

For example:

<my:panel title="Student Details">
    <p>This is the content inside the panel.</p>
</my:panel>

For a Java simple tag handler, the body can be represented by a JspFragment. The handler can invoke the fragment to render the body when appropriate.

Example: A Simple Panel Tag

package com.example.tags;

import java.io.IOException;
import jakarta.servlet.jsp.JspException;
import jakarta.servlet.jsp.JspWriter;
import jakarta.servlet.jsp.tagext.JspFragment;
import jakarta.servlet.jsp.tagext.SimpleTagSupport;

public class PanelTag extends SimpleTagSupport {

    private String title;

    public void setTitle(String title) {
        this.title = title;
    }

    @Override
    public void doTag() throws JspException, IOException {
        JspWriter out = getJspContext().getOut();

        out.write("<section class=\"panel\">");
        out.write("<h2>");
        out.write(escapeHtml(title == null ? "Panel" : title));
        out.write("</h2>");

        JspFragment body = getJspBody();
        if (body != null) {
            body.invoke(out);
        }

        out.write("</section>");
    }

    private String escapeHtml(String value) {
        return value
            .replace("&", "&amp;")
            .replace("<", "&lt;")
            .replace(">", "&gt;")
            .replace(""", "&quot;")
            .replace("'", "'");
    }
}

For this tag, the TLD's body-content declaration should permit a JSP body, such as scriptless, rather than empty. The exact declaration must match the content the tag is designed to accept.

Key point: A simple tag handler can control when its body is invoked. It should not invoke a body fragment more times than the intended behavior requires.

10. Empty, Scriptless, and Tag-Dependent Body Content

The TLD's body-content declaration documents the kind of content a tag is designed to accept.

Body Content Meaning Typical Use
empty The tag does not accept a body. A self-closing formatting or output tag.
scriptless The body may contain template text, EL, and JSP actions, but not scripting elements. A panel or layout tag that wraps page content.
tagdependent The body is treated as content for the tag to interpret rather than as ordinary JSP content. Specialized tags that parse their own body text.

Choose the body-content type based on the tag's intended use and the JSP specification supported by the application server.

11. Custom Tags and Expression Language (EL)

Expression Language makes JSP pages more readable by providing a concise way to access values from supported scopes and evaluate expressions. Custom tags can receive values produced by EL expressions.

<%@ taglib prefix="my" uri="https://example.com/tags" %>

<my:welcome name="${sessionScope.studentName}" />

Here, the value of studentName is obtained from the session scope and passed to the tag. The application should ensure that the value is available and that output is safely escaped by the tag implementation.

12. Custom Tags Compared with JSTL

JSTL provides standard tags for common tasks such as conditional processing, iteration, formatting, and internationalization. Custom tags are useful when the application needs behavior or presentation components that are not conveniently provided by standard libraries.

Feature JSTL Custom JSP Tags
Availability Standard tag library with an appropriate implementation Created by the application team or supplied by a library
Common purpose Iteration, conditions, formatting, and related tasks Application-specific reusable behavior
Setup Requires the appropriate library and taglib declaration Depends on the approach: tag file or Java handler and TLD
Customization Limited to available tags and their supported behavior Can be tailored to the application's requirements

13. Common Applications of Custom JSP Tags

  • Reusable page headers: Display consistent branding and navigation.
  • Form components: Render standard labels, hints, and validation messages.
  • Message panels: Display success, warning, and error messages in a consistent layout.
  • Data presentation: Format values or render repeated display components.
  • Reusable cards: Show product, course, or user information.
  • Layout components: Wrap content inside reusable sections or panels.
  • Application-specific formatting: Apply consistent display rules for values used throughout the site.

14. Custom Tags in the MVC Architecture

In the Model-View-Controller (MVC) architecture, custom JSP tags generally belong to the presentation layer. They help the view display data without putting business rules directly into JSP pages.

  1. Model: Represents application data and business logic.
  2. Controller: Handles requests, invokes application services, and prepares data for the view.
  3. View: Uses JSP, EL, JSTL, and custom tags to render the response.

For example, a controller may retrieve a list of courses and place it in request scope. The JSP page can then use JSTL to iterate over the list and a custom tag to render a reusable course card.

Custom tags should generally focus on presentation and reusable view behavior. Database access, authentication decisions, and core business rules should remain in appropriate application layers.

15. Error Handling and Troubleshooting

Problem Possible Cause Solution
Tag library cannot be found Incorrect TLD URI, taglib directive, or descriptor location Verify the URI and confirm that the TLD is packaged under the web application's expected location.
Tag class cannot be loaded Incorrect package name or class not deployed Check the fully qualified class name and ensure the compiled class is available to the application.
Attribute is not recognized Attribute missing from the TLD or setter name is incorrect Check the TLD declaration and JavaBean setter.
Required attribute is missing The JSP tag invocation omitted a mandatory attribute Supply the required attribute or change the declaration if it is intended to be optional.
Body is rejected The body-content declaration does not match the supplied body Choose a body-content type appropriate to the intended content.
Compilation errors involving packages Mixing Jakarta and older Java EE APIs Use the namespace and API version supported by the target server.
Unexpected output Incorrect attribute value, EL expression, or tag logic Inspect the rendered output, input values, and server logs.
HTML appears incorrectly Invalid markup or unsafe manual output construction Validate markup and use context-appropriate output escaping.

16. Security Considerations

Custom tags often render values originating from users, databases, request parameters, or session attributes. Incorrect output handling can introduce cross-site scripting (XSS) vulnerabilities.

  • Escape untrusted values before inserting them into HTML text.
  • Use context-aware encoding for HTML attributes, URLs, JavaScript, and CSS; HTML text escaping alone is not sufficient for every context.
  • Validate input according to the application's requirements.
  • Do not treat HTML escaping as a replacement for authorization or input validation.
  • Avoid placing database queries or sensitive business logic inside presentation tags.
  • Do not expose confidential application data through custom tag output.
  • Use established libraries for encoding when handling complex output contexts.
  • Test tags with empty strings, special characters, unexpected values, and malicious-looking input.

17. Best Practices for Developing Custom JSP Tags

  • Use custom tags only when they provide meaningful reuse or improve clarity.
  • Give tags clear, descriptive names.
  • Define attributes explicitly and document their purpose.
  • Use tag files for straightforward presentation fragments.
  • Use Java tag handlers when Java processing is genuinely needed.
  • Keep business logic and persistence operations outside the JSP presentation layer.
  • Handle missing or optional values predictably.
  • Use the correct body-content declaration.
  • Escape untrusted output according to its destination context.
  • Keep TLD definitions, Java classes, and JSP usage consistent.
  • Test tags independently and within the pages that use them.
  • Use Jakarta or legacy Java EE APIs consistently with the chosen server version.

18. Practical Exercise

Task: Create a custom JSP tag named statusMessage that displays a message with a status type such as success, warning, or error.

Requirements

  1. Create a Java tag handler or a tag file.
  2. Define a required message attribute.
  3. Define a type attribute that accepts values such as success, warning, and error.
  4. Render the message inside an HTML container.
  5. Apply a CSS class based on the status type.
  6. Escape the message safely before rendering it.
  7. Test the tag with ordinary text, empty values, and special characters.

Example Usage

<my:statusMessage
    type="success"
    message="Your profile was updated successfully." />

<my:statusMessage
    type="warning"
    message="Please review your profile details." />

Expected Learning Outcome

After completing this exercise, you should understand how tag attributes customize output, how reusable presentation logic reduces duplication, and why output encoding is important.

19. Mini Project: Reusable Course Information Tags

Create a small JSP-based course listing page that uses custom tags to display course information consistently.

Project Features

  • A reusable course-card tag.
  • Attributes for course title, duration, and level.
  • A reusable message tag for success and error notifications.
  • JSTL iteration for displaying multiple courses.
  • EL for accessing values prepared by the controller.
  • Consistent HTML markup and CSS styling.
  • Output escaping for user-controlled or externally sourced text.

Suggested Project Structure

src/main/java/
    com/example/tags/
        CourseCardTag.java

src/main/webapp/
    WEB-INF/
        my-tags.tld
        tags/
            message.tag
    courses.jsp
    css/
        styles.css

The exact structure can vary depending on the build tool and framework used. A Maven project may use src/main/webapp for web resources and src/main/java for Java classes.

20. Interview Questions and Answers

Q1. What is a custom JSP tag?

Answer: A custom JSP tag is a user-defined tag that encapsulates reusable presentation logic or application-specific view behavior for use in JSP pages.

Q2. Why are custom JSP tags used?

Answer: They reduce repeated code, improve readability, support reuse, and help separate presentation logic from the main JSP page.

Q3. What are the main ways to create custom JSP tags?

Answer: The common approaches are JSP tag files and Java-based tag handlers.

Q4. What is a Tag Library Descriptor?

Answer: A TLD is an XML descriptor that defines a tag library, including tag names, handler classes, attributes, and body-content settings.

Q5. What is the purpose of the JSP taglib directive?

Answer: It makes a tag library available to a JSP page under a specified prefix. The prefix is used to invoke tags from that library.

Q6. What is SimpleTagSupport?

Answer: SimpleTagSupport is a convenience base class for Java-based simple JSP tag handlers. Developers commonly override doTag() to implement the tag's behavior.

Q7. What is the difference between a tag file and a Java tag handler?

Answer: A tag file defines a reusable tag using JSP tag syntax, while a Java tag handler implements the tag's behavior in Java. Tag files are often convenient for presentation fragments; Java handlers are useful for programmatic processing.

Q8. How are attributes defined in a Java tag handler?

Answer: A handler typically declares a field and a public setter method. The TLD declares the attribute name and relevant settings.

Q9. What is the purpose of JspFragment?

Answer: In the simple tag API, JspFragment represents a tag body that can be invoked by the handler to render its content.

Q10. Can custom tags contain a body?

Answer: Yes. A tag can be designed to accept body content. Its TLD or tag-file configuration must match the intended body content.

Q11. How can custom tags improve MVC design?

Answer: They support reusable view components and help keep presentation code organized, while business logic remains in the model or service layer.

Q12. What security issue should custom tag developers consider?

Answer: Cross-site scripting can occur if untrusted data is inserted into HTML without appropriate context-aware output encoding.

Q13. What is the difference between simple and classic tag handlers?

Answer: Simple tag handlers commonly extend SimpleTagSupport and implement doTag(). Classic tag handlers use a different lifecycle, including methods such as doStartTag() and doEndTag().

Q14. When should developers use JSTL instead of a custom tag?

Answer: JSTL is generally suitable for standard tasks such as iteration, conditions, and formatting. A custom tag is appropriate when the application needs reusable behavior not adequately covered by the available standard tags.

Q15. Which package namespace should modern Jakarta JSP applications use?

Answer: Modern Jakarta-based applications use packages such as jakarta.servlet.jsp. Older Java EE applications use javax.servlet.jsp. The code must match the target server and API version.

21. Quick Revision Checklist

  • Understand what custom JSP tags are and why they are useful.
  • Know the differences between tag files and Java tag handlers.
  • Know the role of the TLD file.
  • Understand how the JSP taglib directive works.
  • Know how attributes are declared and supplied.
  • Understand the simple tag lifecycle and the role of doTag().
  • Know how a simple tag handler can access body content through JspFragment.
  • Choose an appropriate body-content declaration.
  • Use EL and JSTL where appropriate.
  • Keep business logic outside presentation tags.
  • Apply context-aware output encoding.
  • Test custom tags for missing values and incorrect configuration.

22. Conclusion

Creating and using custom JSP tags is an important Advanced Java skill for building maintainable JSP-based web applications. Custom tags allow developers to package repeated presentation behavior into reusable components, simplify JSP pages, and encourage a clearer separation between the view and application logic.

For simple reusable UI fragments, tag files are often a practical starting point. For more programmatic behavior, Java-based tag handlers provide additional flexibility. A well-designed tag should have clear attributes, appropriate body-content rules, predictable behavior, and safe output handling.

23. Learning Resources and Course Links

Previous Next
whatsapp